package com.xnx3.banmahuishou.superadmin.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.BaseVO;
import com.xnx3.DateUtil;
import com.xnx3.Lang;
import com.xnx3.banmahuishou.agency.vo.QishouListVO;
import com.xnx3.banmahuishou.agency.vo.QishouShowVO;
import com.xnx3.banmahuishou.agency.vo.WanggeListVO;
import com.xnx3.banmahuishou.core.entity.Agency;
import com.xnx3.banmahuishou.core.entity.Area;
import com.xnx3.banmahuishou.core.entity.Qishou;
import com.xnx3.banmahuishou.core.entity.Wangge;
import com.xnx3.banmahuishou.core.util.AreaUtil;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.LanguageUtil;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.wangmarket.shop.core.entity.Order;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 代理商管理
 * @author 王晓龙
 */
@Controller(value="BanmahuishouSuperadminAgencyController")
@RequestMapping("/superadmin/agency/")
public class AgencyController extends BaseController  {
	@Resource
	private SqlService sqlService;
	@Resource
	private UserService userService;

	/**
	 * 代理商列表
	 */
	@RequestMapping("list${url.suffix}")
	public String list(HttpServletRequest request,Model model){
		Sql sql = new Sql(request);
		sql.setSearchColumn(new String[]{"name"});
		sql.appendWhere("(userid IS NULL OR userid = 1)");
		int count = sqlService.count("laji_agency", sql.getWhere());
		Page page = new Page(count, 15, request);
		sql.setSelectFromAndPage("SELECT * FROM laji_agency", page);
		sql.setDefaultOrderBy("laji_agency.id DESC");
		List<Agency> list = sqlService.findBySql(sql, Agency.class);
		ActionLogUtil.insert(request, "代理商管理", "第"+page.getCurrentPageNumber()+"页");

		model.addAttribute("page", page);
		model.addAttribute("list", list);
		return "/superadmin/agency/list";
	}

	/**
	 * 新增/修改
	 * @param id 要修改的id 。 如果是新增，这里传入0或者不传
	 */
	@RequestMapping("edit${url.suffix}")
	public String edit(
			@RequestParam(value = "id", required = false, defaultValue="0") int id,
			Model model, HttpServletRequest request){
		Agency entity;

		if(id < 1){
			//新增
			entity = new Agency();
			ActionLogUtil.insert(request, "进入代理商新增页面");
		}else{
			//修改
			entity = sqlService.findById(Agency.class, id);
			if(entity == null){
				return error(model, "要修改的代理商不存在");
			}
			ActionLogUtil.insert(request, "进入修改代理商页面", entity.toString());
		}

		//编辑页面
		model.addAttribute("entity", entity);
		return "/superadmin/agency/edit";
	}

	/**
	 * 新增、修改的进行保存
	 */
	@RequestMapping(value = "save.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO variableSave(Agency inputEntity, HttpServletRequest request){
		Agency entity = null;			

		if(inputEntity.getId() == null || inputEntity.getId() < 1){
			//新增
			entity = new Agency();

			//因为是新增，所以要加上新增时间
			entity.setAddtime(DateUtil.timeForUnix10());	
		}else{
			//修改
			entity = sqlService.findById(Agency.class, inputEntity.getId());
			if(entity == null){
				return error("要修改的目标不存在");
			}
		}

		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String district = request.getParameter("district");
		if(!StringUtils.hasLength(inputEntity.getName())) {
			return error("请输入代理商名称");
		}
		if(!StringUtils.hasLength(province)) {
			return error("请选择省");
		}
		if(!StringUtils.hasLength(city)) {
			return error("请选择市");
		}
		if(!StringUtils.hasLength(district)) {
			return error("请选择区");
		}
		if(!StringUtils.hasLength(inputEntity.getPhone())) {
			return error("请输入手机号");
		}
		if(!StringUtils.hasLength(inputEntity.getContactName())) {
			return error("请输入负责人");
		}
		if(!StringUtils.hasLength(inputEntity.getEmail())) {
			return error("请输入邮箱");
		}
		//保存
		entity.setUserid(1);
		entity.setName(inputEntity.getName());
		entity.setPhone(inputEntity.getPhone());
		entity.setAddminArea(province + "," + city + "," + district);
		entity.setContactName(inputEntity.getContactName());
		entity.setEmail(inputEntity.getEmail());
		sqlService.save(entity);

		ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "保存代理商信息", entity.toString());
		return success();
	}

	/**
	 * 删除代理商信息
	 */
	@RequestMapping(value="delete.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO delete(@RequestParam(value = "id", required = false, defaultValue="0") int id, HttpServletRequest request){
		Agency entity = sqlService.findById(Agency.class, id);
		if(entity == null){
			return error("要删除的目标不存在");
		}
		sqlService.delete(entity);

		ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "删除代理商", entity.toString());
		return success();
	}

	/**
	 * 代理商(v2)列表
	 */
	@RequestMapping("listv2${url.suffix}")
	public String listv2(HttpServletRequest request,Model model){
		Sql sql = new Sql(request);
		sql.setSearchColumn(new String[]{"name"});
		sql.appendWhere("userid IS NOT NULL AND userid > 1 AND state = " + Agency.STATE_NORMAL);
		int count = sqlService.count("laji_agency", sql.getWhere());
		Page page = new Page(count, 15, request);
		sql.setSelectFromAndPage("SELECT * FROM laji_agency", page);
		sql.setDefaultOrderBy("laji_agency.id DESC");
		List<Agency> list = sqlService.findBySql(sql, Agency.class);

		ActionLogUtil.insert(request, "代理商管理", "第"+page.getCurrentPageNumber()+"页");

		model.addAttribute("page", page);
		model.addAttribute("list", list);
		return "/superadmin/agency/listv2";
	}

	/**
	 * 新增/修改代理商信息(v2)
	 * @param id 要修改的id 。 如果是新增，这里传入0或者不传
	 */
	@RequestMapping("editv2${url.suffix}")
	public String editv2(
			@RequestParam(value = "id", required = false, defaultValue="0") int id,
			Model model, HttpServletRequest request){
		Agency entity;

		if(id < 1){
			//新增
			entity = new Agency();
			ActionLogUtil.insert(request, "进入代理商新增页面");
		}else{
			//修改
			entity = sqlService.findById(Agency.class, id);
			if(entity == null){
				return error(model, "要修改的代理商不存在");
			}
			ActionLogUtil.insert(request, "进入修改代理商页面", entity.toString());
		}
		
		//编辑页面
		model.addAttribute("entity", entity);
		// 行政区划代码
		JSONArray shengArray = JSONArray.fromObject(entity.getShengCode());
		JSONArray shiArray = JSONArray.fromObject(entity.getShiCode());
		JSONArray quArray = JSONArray.fromObject(entity.getQuCode());
		JSONObject jsonObject = new JSONObject();
		if (shengArray.size() > 0) {
			jsonObject.put("provinces", shengArray);
		}
		if (shiArray.size() > 0) {
			jsonObject.put("cities", shiArray);
		}
		if (quArray.size() > 0) {
			jsonObject.put("counties", quArray);
		}
		model.addAttribute("areaCodes", jsonObject);
		System.err.println(jsonObject);
		// 省市区回显
		model.addAttribute("sheng", shengArray.toString().substring(1, shengArray.toString().length() - 1));
		model.addAttribute("city", shiArray.toString().substring(1, shiArray.toString().length() - 1));
		model.addAttribute("qu", quArray.toString().substring(1, quArray.toString().length() - 1));
		
		return "/superadmin/agency/editv2";
	}

	
	

	
	/**
	 * 新增、修改的代理商信息进行保存(v2)
	 */
	@RequestMapping(value="savev2.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO variableSavev2(Agency inputEntity, HttpServletRequest request){
		
		/*
		   	辽宁省,无锡市,奎文区
			{"provinces":["210000"],"cities":["320200"],"counties":["370705"]}
		 */
		String areaNames = request.getParameter("areaNames");
		System.err.println(areaNames);
		String areaCodes = request.getParameter("areaCodes");
		System.err.println(areaCodes);
		
		if (areaCodes == null || areaCodes.length() <= 0) {
			return error("请选择代理的区域");
		}
		if(!StringUtils.hasLength(inputEntity.getName())) {
			return error("请输入代理商名称");
		}
		if(!StringUtils.hasLength(inputEntity.getPhone())) {
			return error("请输入手机号");
		}
		if(!StringUtils.hasLength(inputEntity.getContactName())) {
			return error("请输入负责人");
		}
		if(!StringUtils.hasLength(inputEntity.getEmail())) {
			return error("请输入邮箱");
		}
		JSONObject jsonObject = JSONObject.fromObject(areaCodes);
		
		// 通过新增/修改获取代理商信息
		String sql = "";
		if(inputEntity.getId() != null) {
			 sql = "SELECT * FROM laji_agency WHERE id != " + inputEntity.getId() + " AND  state = " + Agency.STATE_NORMAL;
		}else {
			 sql = "SELECT * FROM laji_agency WHERE state = " + Agency.STATE_NORMAL;
		}
		
		List<Agency> agencyList = sqlService.findBySqlQuery(sql, Agency.class);
		List<String> shengList = new ArrayList<String>();
		List<String> shiList = new ArrayList<String>();
		List<String> quList = new ArrayList<String>();
		
		for (Agency agency : agencyList) {
			if (agency.getShengCode() != null && agency.getShengCode().length() > 1 && agency.getShiCode() != null && agency.getShiCode().length() > 1 && agency.getQuCode() != null && agency.getQuCode().length() > 1) {
				
				JSONArray shengArray = JSONArray.fromObject(agency.getShengCode());
				for (Object string : shengArray) {
					shengList.add(string.toString());
				}
				
				JSONArray shiArray = JSONArray.fromObject(agency.getShiCode());
				for (Object string : shiArray) {
					shiList.add(string.toString());
				}
				
				JSONArray quArray = JSONArray.fromObject(agency.getQuCode());
				for (Object string : quArray) {
					quList.add(string.toString());
				}
			}
		}
		
		// 最多只能代理一个省
		Object provincesObject = jsonObject.get("provinces");
		if (provincesObject != null) {
			JSONArray provinces = jsonObject.getJSONArray("provinces");
			if (provinces != null && provinces.size() > 1) {
				return error("不可同时代理多个省");
			}
			if (shengList.contains(provinces.get(0))) {
				return error("该地区已有代理商,请选择其他区域");
			}
		}
		
		
		// 不可跨省代理市
		Object citiesObject = jsonObject.get("cities");
		if (citiesObject != null) {
			JSONArray cities = jsonObject.getJSONArray("cities");
			if (cities.size() > 0) {
				String oneCity = cities.get(0).toString();
				oneCity = oneCity.substring(0, 2);
				for (Object city : cities) {
					if (!ObjectUtils.equals(oneCity, city.toString().substring(0, 2))) {
						return error("不可跨省代理市");
					}
					if (shiList.contains(city)) {
						return error("该地区已有代理商,请选择其他区域");
					}
				}
			}
		}
		
		// 不可跨市代理区
		Object countiesObject = jsonObject.get("counties");
		if (countiesObject != null) {
			JSONArray counties = jsonObject.getJSONArray("counties");
			if (counties.size() > 0) {
				String oneCounty = counties.get(0).toString();
				oneCounty = oneCounty.substring(0, 4);
				for (Object county : counties) {
					if (!ObjectUtils.equals(oneCounty, county.toString().substring(0, 4))) {
						return error("不可跨市代理区");
					}
					if (quList.contains(county)) {
						return error("该地区已有代理商,请选择其他区域");
					}
				}
			}
		}
		
		// 不能选择一个省和一个\多个其他省的市
		if (provincesObject != null && citiesObject != null) {
			JSONArray provinces = jsonObject.getJSONArray("provinces");
			JSONArray cities = jsonObject.getJSONArray("cities");
			// 获取省代码前两位
			String province = provinces.get(0).toString();
			province = province.substring(0, 2);
			for (Object city : cities) {
				if (!ObjectUtils.equals(province, city.toString().substring(0, 2))) {
					return error("不可跨省代理");
				}
			}
		}
		
		// 不能选择一个省和一个\多个其他省的区
		if (provincesObject != null && countiesObject != null) {
			JSONArray provinces = jsonObject.getJSONArray("provinces");
			JSONArray counties = jsonObject.getJSONArray("counties");
			// 获取省代码前两位
			String province = provinces.get(0).toString();
			province = province.substring(0, 2);
			for (Object county : counties) {
				if (!ObjectUtils.equals(province, county.toString().substring(0, 2))) {
					return error("不可跨省代理");
				}
			}
		}
		
		// 不能选择多个市且同时一个\多个区
		if (citiesObject != null && countiesObject != null) {
			JSONArray cities = jsonObject.getJSONArray("cities");
			JSONArray counties = jsonObject.getJSONArray("counties");
			// 如果市有多个,那么不能选择区,这个时候区应该是全部
			if (cities.size() > 1 && counties.size() > 0) {
				return error("不可跨市代理");
			}
			if (cities.size() == 1  && counties.size() > 0) {
				// 获取市代码前四位
				String city = cities.get(0).toString();
				city = city.substring(0, 4);
				for (Object county : counties) {
					if (!ObjectUtils.equals(city, county.toString().substring(0, 4))) {
						return error("不可跨市代理区");
					}
				}
			}
		}
		// 省市区名称
		String province = "";
		String city = "";
		String district = "";
		// 省市区 区划代码
		JSONArray shengCode = new JSONArray();
		JSONArray shiCode = new JSONArray();
		JSONArray quCode = new JSONArray();
		
		// 获取行政区划代码字典
		Map<Integer, Area> areaMap = AreaUtil.areaMap;
		// 省代理
		if (provincesObject != null && citiesObject == null && countiesObject == null) {
			shengCode = jsonObject.getJSONArray("provinces");
			province = areaNames;
			city = "全部";
			district = "全部";
			// 判断该省下的某个市或者区是否已有代理商
			// 先获取该省下的所有市
			List<Area> list = sqlService.findByProperty(Area.class, "areaParentId", Integer.valueOf(shengCode.get(0).toString()));
			// 存市id
			StringBuffer buffer = new StringBuffer("-1");
			// 循环遍历代理商的市code中有没有上边的市
			for (Area area : list) {
				buffer.append("," + area.getId());
				// 如果数据库中的市代理有该省下的市,就打回
				if (shiList.contains(area.getId().toString())) {
					return error("该省下的【" + area.getAreaName() + "】已有代理商");
				}
			}
			// 获取该省下的所有区
			String string = "SELECT * FROM sys_area WHERE area_parent_id IN(" + buffer + ")";
			list = sqlService.findBySqlQuery(string, Area.class);
			for (Area area : list) {
				// 如果数据库中的区代理有该省下的区,就打回
				if (quList.contains(area.getId().toString())) {
					return error("该省下的【" + area.getAreaName() + "】已有代理商");
				}
			}
		}
		// 市代理
		if (provincesObject == null && citiesObject != null && countiesObject == null) {
			// 根绝行政区划代码查找省名称
			shiCode = jsonObject.getJSONArray("cities");
			Integer integer = Integer.valueOf(shiCode.get(0).toString());
			Area shiArea = areaMap.get(integer);
			if (shiArea == null) {
				return error("市信息出现错误");
			}
			Area shengArea = areaMap.get(shiArea.getAreaParentId());
			if (shengArea == null) {
				return error("省信息出现错误");
			}
			if (shengList.contains(shengArea.getId().toString())) {
				return error("【" + shengArea.getAreaName() +  "】已有代理商,请选择其他区域");
			}
			province = shengArea.getAreaName();
			city = areaNames;
			district = "全部";
			
			// 判断该市下的某个区是否已有代理商
			// 先获取该市下的所有区
			List<Area> list = sqlService.findByProperty(Area.class, "areaParentId", Integer.valueOf(shiCode.get(0).toString()));
			// 循环遍历区看看数据库中的区代理中有没有
			for (Area area : list) {
				// 如果数据库中的区代理有该市下的区,就打回
				if (quList.contains(area.getId().toString())) {
					return error("该市下的【" + area.getAreaName() + "】已有代理商");
				}
			}
		}
		// 区代理
		if (provincesObject == null && citiesObject == null && countiesObject != null) {
			// 根绝行政区划代码查找省\市名称
			quCode = jsonObject.getJSONArray("counties");
			Integer integer = Integer.valueOf(quCode.get(0).toString());
			Area quArea = areaMap.get(integer);
			if (quArea == null) {
				return error("区信息出现错误");
			}
			Area shiArea = areaMap.get(quArea.getAreaParentId());
			if (shiArea == null) {
				return error("市信息出现错误");
			}
			if (shiList.contains(shiArea.getId().toString())) {
				return error("【" + shiArea.getAreaName() +  "】已有代理商,请选择其他区域");
			}
			city = shiArea.getAreaName();
			Area shengArea = areaMap.get(shiArea.getAreaParentId());
			if (shengArea == null) {
				return error("省信息出现错误");
			}
			if (shengList.contains(shengArea.getId().toString())) {
				return error("【" + shengArea.getAreaName() +  "】已有代理商,请选择其他区域");
			}
			province = shengArea.getAreaName();
			district = areaNames;
		}
		
		Agency entity = null;			

		if(inputEntity.getId() == null || inputEntity.getId() < 1){
			//新增
			entity = new Agency();

			//新增一个代理商用户
			User user = new User();
			// 判断手机号是否合法
			if(!isMobiPhoneNum(inputEntity.getPhone())) {
				return error("手机号不合法");
			}
			// 判断手机号唯一性使用
			user.setUsername(inputEntity.getPhone());
			user.setPassword(Lang.uuid());
			user.setNickname(inputEntity.getName());
			user.setPhone(inputEntity.getPhone());
			user.setHead("http://cdn.banxma.com/file/images/a63f71f4eea14157975b6fee1a188cb1.png");
			user.setAuthority("1");
			user.setRegtime(DateUtil.timeForUnix10());
			user.setAllSellWgight(0);
			user.setAllOrderNumbe(0);
			user.setAllIncomeMone(0);
			user.setMoney(0);
			user.setFreezemoney(0);
			user.setEmail(inputEntity.getEmail());
			BaseVO createUserVO = userService.createUser(user, request);
			if(createUserVO.getResult() - BaseVO.FAILURE == 0){
				return error(createUserVO.getInfo());
			}
			entity.setUserid(Lang.stringToInt(createUserVO.getInfo(), 0));
			ActionLogUtil.insertUpdateDatabase(request, user.getId(), "保存代理商信息", user.toString());
			//因为是新增，所以要加上新增时间
			entity.setAddtime(DateUtil.timeForUnix10());	
		}else{
			//修改
			entity = sqlService.findById(Agency.class, inputEntity.getId());
			if(entity == null){
				return error("要修改的目标不存在");
			}
			// 修改之前先判断传入的手机号是否已有 后台 用户在使用
			if(inputEntity.getPhone() != null && inputEntity.getPhone().length() > 0){
				if(findByPhone(inputEntity.getPhone(),entity.getUserid()) != null){
					return BaseVO.failure(LanguageUtil.show("user_regFailureForPhoneAlreadyExist"));
				}
			}
			// 判断手机号是否合法
			if(!isMobiPhoneNum(inputEntity.getPhone())) {
				return error("手机号不合法");
			}
			
			User user = sqlService.findById(User.class, entity.getUserid());
			user.setUsername(inputEntity.getPhone());
			user.setNickname(inputEntity.getName());
			user.setPhone(inputEntity.getPhone());
			user.setEmail(inputEntity.getEmail());
			sqlService.save(user);
		}
		
		if(!StringUtils.hasLength(province)) {
			return error("请选择省");
		}
		if(!StringUtils.hasLength(city)) {
			return error("请选择市");
		}
		if(!StringUtils.hasLength(district)) {
			return error("请选择区");
		}
		//保存
		entity.setName(inputEntity.getName());
		entity.setPhone(inputEntity.getPhone());
		//代理商区域格式 如山东省、山东省潍坊市、山东省潍坊市寒亭区
		if(city.equals("全部")) {
			entity.setAddminArea( province );
		}else if (district.equals("全部")) {
			entity.setAddminArea( province + city );
		}else {
			entity.setAddminArea( province + city + district);
		}
		
		entity.setSheng(province);
		entity.setShi(city);
		entity.setQu(district);
		entity.setShengCode(shengCode.toString());
		entity.setShiCode(shiCode.toString());
		entity.setQuCode(quCode.toString());
		entity.setContactName(inputEntity.getContactName());
		entity.setEmail(inputEntity.getEmail());
		entity.setState(Agency.STATE_NORMAL);
		entity.setMoney(0);
		sqlService.save(entity);

		ActionLogUtil.insertUpdateDatabase(request, entity.getId(), "保存代理商信息", entity.toString());
		return success();
	}

	/**
	 * 删除代理商信息(v2)
	 */
	@RequestMapping(value="deletev2.json", method = RequestMethod.POST)
	@ResponseBody
	public BaseVO deletev2(@RequestParam(value = "id", required = false, defaultValue="0") int id, HttpServletRequest request){
		Agency entity = sqlService.findById(Agency.class, id);
		if(entity == null){
			return error("要删除的目标不存在");
		}

		String sql = "SELECT * FROM laji_wangge WHERE state = "+ Wangge.STATE_NORMAL +" AND dailishang_userid = " + entity.getUserid();
		List<Wangge> list = sqlService.findBySqlQuery(sql, Wangge.class);
		if(list.isEmpty() && list.size()==0) {
			userService.freezeUser(entity.getUserid());
			entity.setState(Agency.STATE_FROZEN);

			ActionLogUtil.insertUpdateDatabase(request, id, "总管理后台-冻结代理商", "冻结了代理商："+entity.toString());

			sqlService.save(entity);
			return success("操作成功！");
		}else {
			return error("该代理商下有网格,不能删除");
		}
	}
	/**
	 * 查看电子围栏
	 * @param sheng 所在的省,如： 山东省
	 * @param shi 所在的市，如 潍坊市
	 * @param qu 所在的区，如 寒亭区
	 * @param userid 代理商用户ID
	 * @author zxy
	 */
	@RequestMapping(value = "check${url.suffix}")
	public String check(HttpServletRequest request,Model model,
			@RequestParam(value = "sheng", required = false, defaultValue = "") String sheng,
			@RequestParam(value = "shi", required = false, defaultValue = "") String shi,
			@RequestParam(value = "qu", required = false, defaultValue = "") String qu,
			@RequestParam(value = "userid", required = true , defaultValue = "") int userid) {
		//判断是否是全省代理
		if ( shi.equals("全部") && qu.equals("全部") && !sheng.isEmpty() ) {
			model.addAttribute( "area" , sheng );
		}else {
			//判断是否只是区代理
			if ( !qu.equals("全部") ) {
				model.addAttribute( "area" , qu );
			}else {
				//判断是否市代理
				if( qu.equals("全部") && !(shi.isEmpty()) ){
					model.addAttribute( "area" , shi );
				}
			}
		}
		model.addAttribute("userid", userid);
		//日志管理
		ActionLogUtil.insert( request , "总管理后台-代理商管理" + "查看电子围栏" );
		//电子围栏展示页面
		return "/superadmin/agency/check";
	}
	/**
	 * 地图展示
	 * @author zxy
	 */
	@RequestMapping(value = "checkAll${url.suffix}")
	public String checkAll(HttpServletRequest request,Model model) {
		//查代理商表
		String sql = "SELECT * FROM laji_agency WHERE userid IS NOT NULL AND userid > 1 AND state = " + Agency.STATE_NORMAL;
		List<Agency> list = sqlService.findBySqlQuery(sql, Agency.class);
		StringBuffer str = new StringBuffer();
		for (Agency agency : list) {
			// 省代理
			if (ObjectUtils.equals(agency.getShi(), "全部")) {
				str.append(agency.getSheng() + ",");
			}
			//区代理
			if (!ObjectUtils.equals(agency.getQu(), "全部")) {
				str.append(agency.getQu() + ",");
			}
			//市代理
			if (ObjectUtils.equals(agency.getQu(), "全部") && !ObjectUtils.equals(agency.getShi(), "全部")) {
				str.append(agency.getShi() + ",");
			}
			if (str.length() > 1) {
				String area = str.substring( 0 , str.length() - 1 );
				model.addAttribute( "area" , area );
			}
		}
		//日志记录
		ActionLogUtil.insert( request , "总管理后台-代理商管理" + "地图展示");
		//地图展示页面
		return "/superadmin/agency/checkAll";
	}
	/**
	 * 获取当前登录用户所能看的所有网格电子围栏的数据信息
	 * @author zxy
	 * @return 电子围栏的信息
	 */
	@ResponseBody
	@RequestMapping(value = "getWanggeAll.json",method = {RequestMethod.POST})
	public WanggeListVO getWanggeAll(HttpServletRequest request,Model model) {
		WanggeListVO vo = new WanggeListVO();
		//获取所有代理商的网格区域
		List<Wangge> list = sqlService.findBySqlQuery("SELECT * FROM laji_wangge WHERE dailishang_userid IS NOT NULL AND dailishang_userid > 1 AND state = " + Wangge.STATE_NORMAL , Wangge.class);
		vo.setList(list);
		//日志记录
		ActionLogUtil.insert( request , "获取了当前用户所能看的所有网格电子围栏数据" );
		return vo;
	}
	/**
	 * 获取所查看的代理商下的所有网格区域
	 * @author zxy
	 * @return 网格区域信息
	 */
	@ResponseBody
	@RequestMapping(value = "getWangge.json",method = {RequestMethod.POST})
	public WanggeListVO getWangge(HttpServletRequest request,Model model) {
		WanggeListVO vo = new WanggeListVO();
		//获取所选代理商所有网格区域
		String userid = request.getParameter("userid");
		List<Wangge> list = sqlService.findBySqlQuery("SELECT * FROM laji_wangge WHERE dailishang_userid = " + userid + " AND state = " + Wangge.STATE_NORMAL , Wangge.class);
		vo.setList(list);
		//日志记录
		ActionLogUtil.insert( request , "获取代理商id为" + userid + "的代理商代理区域下的所有电子网格" );
		return vo;
	}
	/**
	 * 获取当前用户所有能查看的骑手数据(地图展示内)
	 * @author zxy
	 * @return 电子网格数据
	 */
	@ResponseBody
	@RequestMapping(value = "getQishouAll.json",method = {RequestMethod.POST})
	public QishouListVO getQishouAll(HttpServletRequest request,Model model) {
		QishouListVO vo = new QishouListVO();
		List<QishouShowVO> showList = new ArrayList<QishouShowVO>();
		int userid = getUserId();	//当前用户的userid
		//列出所有工作状态正常的骑手集合
		String sql = "SELECT * FROM laji_qishou WHERE dailishang_userid IS NOT NULL AND wangge_userid IS NOT NULL AND state = " + Qishou.STATE_NORMAL ;
		List<Qishou> list = sqlService.findBySqlQuery( sql, Qishou.class);
		if (!list.isEmpty()) {
			for (Qishou qishou : list) {
				QishouShowVO showvo = new QishouShowVO();
				showvo.setLatitude(qishou.getLatitude());
				showvo.setLongitude(qishou.getLongitude());
				showvo.setQishouid(qishou.getId());
				int count = sqlService.count("shop_order", " WHERE qishou_id = " + qishou.getId() +  " AND state = " + Order.STATE_DAIQUHUO + " AND reserve_end_time >= " + DateUtil.timeForUnix10());
				showvo.setCount(count);
				showvo.setQishouName(qishou.getName());
				showvo.setWanggeName(qishou.getWanggeUsername());
				showList.add(showvo);
			}
		}
		vo.setList(showList); 
		//日志记录
		ActionLogUtil.insert( request , "id为" + userid + "的用户查看了所有的骑手数据" );
		return vo;
	}
	/**
	 * 获取当前用户所有能查看的骑手数据(查看电子围栏内)
	 * @author zxy
	 * @return 电子网格数据
	 */
	@ResponseBody
	@RequestMapping(value = "getQishouDailishang.json",method = {RequestMethod.POST})
	public QishouListVO getQishouDailishang(HttpServletRequest request,Model model) {
		QishouListVO vo = new QishouListVO();
		List<QishouShowVO> showList = new ArrayList<QishouShowVO>();
		int userid = getUserId();	//当前用户的userid
		String dailishangUserid = request.getParameter("id");
		//列出当前代理商下所有工作状态正常的骑手集合
		String sql = "SELECT * FROM laji_qishou WHERE dailishang_userid = " + dailishangUserid + " AND wangge_userid IS NOT NULL AND state = " + Qishou.STATE_NORMAL ;
		List<Qishou> list = sqlService.findBySqlQuery( sql, Qishou.class);
		if (!list.isEmpty()) {
			for (Qishou qishou : list) {
				QishouShowVO showvo = new QishouShowVO();
				showvo.setLatitude(qishou.getLatitude());
				showvo.setLongitude(qishou.getLongitude());
				showvo.setQishouid(qishou.getId());
				int count = sqlService.count("shop_order", " WHERE qishou_id = " + qishou.getId() +  " AND state = " + Order.STATE_DAIQUHUO + " AND reserve_end_time >= " + DateUtil.timeForUnix10());
				showvo.setCount(count);
				showvo.setQishouName(qishou.getName());
				showvo.setWanggeName(qishou.getWanggeUsername());
				showList.add(showvo);
			}
		}
		vo.setList(showList);  
		//日志记录
		ActionLogUtil.insert( request , "id为" + userid + "的用户查看了代理商id为" + dailishangUserid + "下的的骑手数据" );
		return vo;
	}
}
